package com.lc.rocketmq.service;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * @author liuc
 * @date 2021/8/21
 * @description
 **/
@Slf4j
@Component
public class Sender {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    public void send(String tp, Object o){
        String s = JSONObject.toJSONString(o);
        rocketMQTemplate.convertAndSend(tp,s);
    }

    public void sendDelay(String tp, Object o,int delayLevel){
        String s = JSONObject.toJSONString(o);
        Message<String> msg = MessageBuilder.withPayload(s).build();
        rocketMQTemplate.asyncSend(tp, msg, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                //成功 do nothing
                log.info("waiting pay msg send success");
            }

            @Override
            public void onException(Throwable throwable) {
                //异常
                log.error("waiting pay msg send fail, ", throwable);
            }
        },5000,delayLevel);
    }

}
